$.fn.alternateRowColors = function() {
    $('tbody tr:odd', this).removeClass('even').addClass('odd');
    $('tbody tr:even', this).removeClass('odd').addClass('even');
    return this;
};
$(document).ready(function(){
    var alternateRowColors = function($table) {
        $('tbody tr:odd', $table).removeClass('even').addClass('odd');
        $('tbody tr:even', $table).removeClass('odd').addClass('even');
    };
    $('.messages').fadeOut(6500);
    $.ajaxSetup({
        cache: false,
        type: 'POST',
        dataType: 'json',
        error: function () {
            alert('Um erro de comunica��o com o servidor ocorreu!');
            $('#ajax-ldr').fadeOut('fast');
        }
    });
    $('.messages').fadeOut(6500);
    $('.tips').tipsy({
        title:'obs',
        gravity: $.fn.tipsy.autoWE,
        delayIn:100,
        delayOut:100,
        html:true
    });
    $('#insitem').click(function(){
        $.ajax({
            url: "/processos/additem",
            processData: false,
            data: 'processo_id='+$('#id').val()+'&depto_id='+$('#depto_id').val()+'&funcionario_id='+$('#funcionario_id').val()+
                  '&descricao='+escape($('#descitem').val())+'&fim='+$('#fim').attr('checked')+'&checklist_id='+$('#checklist_id').val(),
            beforeSend: function (){
                var pos = $('#insitem').position();
                var width = $('#insitem').width();
                $("#ajax-ldr").css( {
                    "left": (pos.left+width+17) + "px",
                    "top":pos.top + "px"
                } ).fadeIn('fast');
            },
            success: function(msg){
                $('#ajax-ldr').fadeOut('fast');
                $("#wait").fadeOut('fast');
                if (msg['status']==false){
                    alert('Erro adicionando passo ao processo!');
                }
                else{
                    $('#itens tbody')
                    .append($('<tr>').attr('class','MoveableRow')
                        .append($('<td>').text(msg['item'].depto.nm_depto))
                        .append($('<td>').text((msg['item'].funcionario.nome!=null)?msg['item'].funcionario.nome:''))
                        .append($('<td>').text((msg['item'].checklist.descricao!=null)?msg['item'].checklist.descricao:''))
                        .append($('<td>').text(msg['item'].descricao))
                        .append($('<td>').attr('align','center')
                            .append($('<a>').attr('href','/checklistitens/editar/id/'+msg['item'].id)
                                .append($('<span>').attr('class','tips ui-widget-content ui-icon ui-icon-pencil').attr('obs','Editar este Passo'))))
                        .append($('<td>').attr('align','center')
                            .append($('<a>').attr('href','/checklistitens/remover/id/'+msg['item'].id)
                                .append($('<span>').attr('class','tips ui-widget-content ui-icon ui-icon-trash'))))
                        .append($('<td>').attr('align','center')
                            .append($('<a>').attr('href','#').attr('class','mover').attr('iditem',msg['item'].id).attr('direcao','baixo').click(function(){
                                move($(this));
                                return false;
                            })
                            .append($('<span>').attr('class','tips ui-widget-content ui-icon ui-icon-circle-arrow-s'))))
                        .append($('<td>').attr('align','center')
                            .append($('<a>').attr('href','#').attr('class','mover').attr('iditem',msg['item'].id).attr('direcao','cima').click(function(){
                                move($(this));
                                return false;
                            })
                            .append($('<span>').attr('class','tips ui-widget-content ui-icon ui-icon-circle-arrow-n'))))
                        );
                    $('#passo').val('');
                    $('#itens').alternateRowColors();
                }
            }
        });
    });

    function move(e){
        var dir = $(e).attr('direcao');
        var id  = $(e).attr('iditem');
        //alert(dir);
        $.ajax({
            url: "/processos/moveritem",
            processData: false,
            data: 'id='+id+'&direcao='+dir,
            beforeSend: function (){
                var pos = $(e).position();
                var width = $(e).width();
                $("#ajax-ldr").css( {
                    "left": (pos.left+width+17) + "px",
                    "top":pos.top + "px"
                } ).fadeIn('fast');
            },
            success: function(msg){
                $('#ajax-ldr').fadeOut('fast');
                $("#wait").fadeOut('fast');
                if (msg==false){
                    alert('Erro adicionando passo ao checklist!');
                }
                else{
                    if (dir=='baixo'){
                        var rowToMove = $(e).parents('tr.MoveableRow:first');
                        var next = rowToMove.next('tr.MoveableRow')
                        if (next.length == 1) {
                            next.after(rowToMove);
                        }
                    }else{
                        var rowToMove = $(e).parents('tr.MoveableRow:first');
                        var prev = rowToMove.prev('tr.MoveableRow')
                        if (prev.length == 1) {
                            prev.before(rowToMove);
                        }
                    }
                    $('#itens').alternateRowColors();
                }
            }
        });
    }

    $('.mover').click(function(){
        move($(this));
        return false;
    });
    $('#depto_id').change(function(){
        if ($('#depto_id').val()!=''){
            $.ajax({
                url: "/funcionarios/index",
                processData: false,
                data: 'id_depto='+$('#depto_id').val(),
                beforeSend: function (){
                    var pos = $('#depto_id').position();
                    var width = $('#depto_id').width();
                    $("#ajax-ldr").css( {
                        "left": (pos.left+width+5) + "px",
                        "top":pos.top + "px"
                    } ).fadeIn('fast');

                },
                success: function(msg){
                    $('#funcionario_id option').remove();
                    $('#funcionario_id').append("<option value=''>Selecione o Funcion�rio...</option>")
                    for (i = 0; i < msg.length; i++) {
                        $('#funcionario_id').append("<option value='"+msg[i].id+"'>"+msg[i].nome+"</option>")
                    }
                    $('#ajax-ldr').fadeOut('fast');
                }
            });
        }
    });
});